package com.credithc.signature.callback.mq.retry;

import com.credithc.signature.callback.service.MessageService;
import com.credithc.signature.common.ro.callback.CallbackReq;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@Slf4j
@Component
public class RetryConsumer {

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

    @Autowired
    MessageService messageService;


    @RabbitListener(queues = "callback_delay_queue", containerFactory = "rabbitListenerContainerFactory")
    public void processDelayMessage(@Payload CallbackReq callbackReq, @Headers Map<String, Object> headers, Message message, Channel channel) throws IOException {
        log.info("接收到延迟队列消息id:{}", message.getMessageProperties().getDeliveryTag());
        try {
            log.info("接收到延迟队列消息流水:requestSn={}", callbackReq.getRequestSN());
            log.debug("CallbackReq = " + callbackReq.toString());
            String takeTime = formatter.format(LocalDateTime.now());
            log.info("开始第{}次重试...... | putTime={},takeTime={}", callbackReq.getRetryTime(), callbackReq.getPutTime(), takeTime);
            // 确认消息成功接收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            messageService.process(callbackReq);
        } catch (Throwable e) {
            log.error("延迟队列－消息－:requestSn={},处理失败...... ", message.getMessageProperties().getDeliveryTag(), e);
            //说明消息处理异常，但是不能重新放入队列，否则变成死循环。
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
